<template>
  <div class="container">
    <!-- <div class="sidebar">
      <a-table
        :columns="columns"
        :data="treeData"
        :pagination="false"
        @row-click="rowClickFunc"
        class="my-table"
      >
        <template #tr="{ record }">
          <tr :class="actRow === record.satelliteId ? 'my-tr' : ''"></tr>
        </template>
      </a-table>
    </div> -->
    <div class="main-content">
      <div class="settings">
        <a-button
          type="primary"
          @click="openModal"
          style="width: 100px; float: right; z-index: 99; margin-bottom: 20px; cursor: pointer"
        >
          新建
        </a-button>
        <a-spin :loading="loading">
          <a-table :data="satData" :pagination="false">
            <template #columns>
              <a-table-column title="序号" data-index="satName" width="70">
                <template #cell="{ rowIndex }">
                  {{ rowIndex + 1 }}
                </template>
              </a-table-column>
              <a-table-column title="模型名称" data-index="name" width="120"></a-table-column>
              <a-table-column title="镜像名称" data-index="imageName" width="250"></a-table-column>
              <a-table-column title="算法执行方法名" data-index="methodName" width="150"></a-table-column>
              <a-table-column title="算法执行代码" data-index="code"></a-table-column>
              <a-table-column title="模型说明" data-index="description" width="150"></a-table-column>
              <a-table-column title="操作" :width="255" align="center">
                <template #cell="{ record }">
                  <a-space size="medium">
                    <!-- <a-button type="text">绑定</a-button>
                    <a-button type="text">解绑</a-button> -->
                    <a-button type="text" @click="editConfigItem(record)"
                      ><template #icon><IconEdit /></template>修改</a-button
                    >
                    <a-button type="text" status="danger" @click="deleteConfigItem(record)"
                      ><template #icon><IconDelete /></template>删除</a-button
                    >
                  </a-space>
                </template>
              </a-table-column>
            </template>
          </a-table>
          <a-pagination
            class="my-1"
            style="float: right; margin-right: 20px; margin-top: 20px; justify-content: end"
            :total="paginationData.total"
            :current="paginationData.pageStart"
            :page-size="paginationData.pageLength"
            show-total
            show-jumper
            show-page-size
            @change="handleCurrentChange"
            @page-size-change="handleSizeChange"
          />
        </a-spin>
      </div>
    </div>
  </div>
  <a-modal
    v-if="showModal"
    v-model:visible="showModal"
    :title="modalTitle"
    @before-ok="handleSubmit"
    @cancel="handleCancel"
    class="modelCont"
    width="50%"
  >
    <a-form :model="form" ref="formRef" class="formData">
      <a-row>
        <a-col :span="22">
          <a-form-item
            label="模型名称"
            field="name"
            label-col-flex="120px"
            :rules="[{ required: true, message: '必填项' }]"
          >
            <a-input v-model="form.name" placeholder="请输入名称"> </a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="22">
          <a-form-item
            label="镜像名称"
            field="imageName"
            label-col-flex="120px"
            :rules="[{ required: true, message: '必选项' }]"
          >
            <a-select v-model="form.imageName" allow-clear placeholder="请选择镜像" value-key="paramId">
              <a-option
                v-for="(item, index) in imageList"
                :key="index"
                :value="item.imageName"
                :label="item.imageName"
              ></a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <!-- <a-col :span="22">
          <a-form-item
            label="算法执行方法名"
            field="methodName"
            label-col-flex="120px"
            :rules="[{ required: true, message: '必填项' }]"
          >
            <a-input
              placeholder="请输入方法名"
              v-model="form.methodName"
            ></a-input>
          </a-form-item>
        </a-col> -->
        <a-col :span="22">
          <a-form-item
            label="模型类型"
            field="type"
            label-col-flex="120px"
            :rules="[{ required: true, message: '必填项' }]"
          >
            <a-select placeholder="请选择模型类型" v-model="form.type" allow-clear>
              <a-option :value="1">机理模型</a-option>
              <a-option :value="2">数据驱动模型</a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="22">
          <a-form-item label="模板" field="value" label-col-flex="120px">
            <a-select
              v-model="form.template"
              allow-clear
              placeholder="请选择模板"
              value-key="id"
              @change="handleTemplateChange"
            >
              <a-option
                v-for="(item, index) in templateList"
                :key="index"
                :value="item"
                :label="item.templateName"
              ></a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="22">
          <a-form-item
            label="代码"
            field="code"
            label-col-flex="120px"
            :rules="[{ required: true, message: '必填项' }]"
          >
            <Editor ref="editorRef" :value="form.code" @update:value="handleUpdateValue" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="22">
          <a-form-item label="模型说明" label-col-flex="120px" field="">
            <a-textarea v-model="form.description" placeholder="请输入模型说明"> </a-textarea>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { apiHome } from '@/api'
import { apiAnalysis } from '@/api/analysis'
import { apiTemplate } from '@/api/complexModel'
import { Message, Modal } from '@arco-design/web-vue'
import Editor from './components/edit.vue'
import Template from '@/views/modelInference/template.vue'
const showModal = ref(false)
const modalTitle = ref('')
// getSelectParams
const columns = [
  {
    title: '卫星',
    dataIndex: 'satelliteName'
  }
]
const paginationData = reactive({
  pageStart: 1,
  pageLength: 10,
  total: 10
})

const loading = ref(false)

const monitorEnmu = reactive([
  {
    id: 1,
    name: '1'
  },
  {
    id: 2,
    name: '2'
  },
  {
    id: 3,
    name: '3'
  },
  {
    id: 4,
    name: '4'
  },
  {
    id: 5,
    name: '5'
  }
])

const form = reactive({})

const actRow = ref(null)
const handleCurrentChange = (val) => {
  paginationData.pageStart = val
  // getTableData();
  getList()
}
const handleSizeChange = (val) => {
  paginationData.pageLength = val
  // getTableData();
  getList()
}
const treeData = ref([])
const satData = ref([])
const getTreeData = () => {
  apiHome.satellites().then((res) => {
    if (+res.code === 200) {
      treeData.value = res.data || []
      actRow.value = res.data[0].satelliteId
      getTableData()
      getSelectParams()
    }
  })
}
const ycParamList = ref([])
const getSelectParams = () => {
  apiHome.getSelectParams({ satId: actRow.value }).then((res) => {
    ycParamList.value = res?.data || []
  })
}
const getTableData = () => {
  loading.value = true
  apiAnalysis
    .getPageList({
      pageNum: 1,
      pageSize: 10,
      satelliteId: actRow.value || 0
    })
    .then((res) => {
      if (+res.code === 200) {
        loading.value = false
        paginationData.total = +res.data?.total || 0
        satData.value = res.data?.list || []
      }
    })
    .finally(() => {
      loading.value = false
    })
}

const getList = () => {
  loading.value = true
  apiTemplate
    .getComplexModelList(paginationData)
    .then((res) => {
      if (+res.code === 200) {
        loading.value = false
        paginationData.total = +res.data?.total || 0
        satData.value = res.data?.list || []
      }
    })
    .finally(() => {
      loading.value = false
    })
}
const imageList = ref([])
const getImageList = () => {
  apiTemplate.getMirrorList().then((res) => {
    if (+res.code === 200) {
      imageList.value = res.data || []
    }
  })
}

const templateList = ref([])
const getTemplateList = () => {
  apiTemplate
    .getList({
      pageStart: 1,
      pageSize: 100
    })
    .then((res) => {
      if (+res.code === 200) {
        templateList.value = res.data.list || []
      }
    })
}

const handleUpdateValue = (newValue) => {
  form.code = newValue
}

const editorRef = ref(null)
const handleTemplateChange = (val) => {
  console.log(val, 'val')
  form.code = val.content
  editorRef.value.setValue(val.content) // 将模板内容赋值给编辑器
  console.log(form.code, 'code')
}

const openModal = () => {
  form.id = ''
  form.name = ''
  form.imageName = ''
  form.methodName = ''
  form.type = ''
  form.code = ''
  form.description = ''
  form.template = ''
  showModal.value = true
  modalTitle.value = '新建模型'
}

const editConfigItem = (row) => {
  // showModal.value = true;
  // form.id =row.id;
  //     form.name = row.name;
  //     form.imageName = row.imageName;
  //     form.methodName = row.methodName;
  //     form.code = row.code;
  //     form.description = row.description;
  apiTemplate.getComplexModelById(row.id).then((res) => {
    if (+res.code === 200) {
      modalTitle.value = '编辑模型'
      showModal.value = true
      form.id = res.data.id
      form.name = res.data.name
      form.imageName = res.data.imageName
      form.methodName = res.data.methodName
      form.type = res.data.type
      form.template = ''
      form.code = res.data.code
      form.description = res.data.description
      console.log(form.code, 'code')
    }
  })
}

const deleteConfigItem = (row) => {
  Modal.confirm({
    title: '删除',
    content: `确定删除${row.name}吗？`,
    onOk: () => {
      apiTemplate.deleteComplexModel(row.id).then((res) => {
        if (+res.code === 200) {
          // getTableData();
          getList()
          Message.success('删除成功')
        }
      })
    }
  })
}

const formRef = ref(null)
const handleSubmit = (done) => {
  formRef.value.validate((errors) => {
    if (!errors) {
      // Object.assign(form, {
      //   deviceCode: form.paramObj.deviceCode,
      //   deviceId: form.paramObj.deviceId,
      //   deviceName: form.paramObj.deviceName,
      //   paramCode: form.paramObj.paramCode,
      //   paramId: form.paramObj.paramId,
      //   paramName: form.paramObj.paramName,
      //   satCode: form.paramObj.satCode,
      //   satId: form.paramObj.satId,
      //   satName: form.paramObj.satName,
      //   subsystemId: form.paramObj.subsystemId,
      //   subsystemName: form.paramObj.subsystemName,
      // });
      // delete form.paramObj;

      const api = form.id ? apiTemplate.updateComplexModel : apiTemplate.saveComplexModel
      api(form).then((res) => {
        if (+res.code === 200) {
          // getTableData();
          // handleCancel();
          getList()
          Message.success(form.id ? '编辑成功' : '新建成功')
          done()
        } else {
          done(false)
        }
      })
    } else {
      console.log('error', errors)
      done(false)
    }
  })
  // form.paramCode = form.paramObj.paramCode
  // form.paramId = form.paramObj.paramId
  // form.paramName = form.paramObj.paramName
  // form.satCode = form.paramObj.satCode
  // form.satId = form.paramObj.satId
  // form.satName = form.paramObj.satName
  // form.subsystemId = form.paramObj.subsystemId
  // form.subsystemName = form.paramObj.subsystemName
  // console.log(form, "111");
}

const handleCancel = () => {
  formRef.value.resetFields()
  showModal.value = false
}

const rowClickFunc = (record) => {
  actRow.value = record.satelliteId
  getTableData()
  getSelectParams()
}

onMounted(() => {
  // getTreeData();
  getList()
  getImageList()
  getTemplateList()
})
</script>

<style lang="less" scoped>
.container {
  display: flex;
  min-height: calc(100vh - 56px);
}

.sidebar {
  width: 250px;
  padding: 20px;
  border-right: 1px solid #f0f0f0;
}
h2 {
  text-align: center;
  font-family:
    Microsoft YaHei,
    Microsoft YaHei,
    serif;
  font-weight: bold;
  font-size: 18px;
  color: #222222;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.settings {
  margin-bottom: 20px;
}
.my-tr {
  background: #1d68d0;
  color: #fff;
  :deep(td) {
    background: #1d68d0;
    color: #fff;
  }
}
.my-tr :hover {
  background: #1d68d0;
  color: #fff;
}
.my-table tr {
  cursor: pointer;
}
:deep(.arco-btn-size-medium) {
  padding: 0;
}
</style>
